##########################################
## Copyright 2012-2013 Ceruti Francesco
##
##
## This file is part of LiSP (Linux Show Player).
##
## LiSP (Linux Show Player) is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## LiSP (Linux Show Player) is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with LiSP (Linux Show Player).  If not, see <http://www.gnu.org/licenses/>.
##########################################

from PyQt4 import QtCore
from PyQt4 import QtGui
from lisp.ui.preferences.preferences_widget import PreferencesWidget
from lisp.ui.qtextinputdialog import QTextInputDialog


class General(PreferencesWidget):

    NAME = 'General'

    def __init__(self, size, parent=None):
        super(General, self).__init__(size, parent)

        self.verticalLayoutWidget = QtGui.QWidget(self)
        self.verticalLayoutWidget.setGeometry(QtCore.QRect(0, 0, 431, 465))
        self.verticalLayout = QtGui.QVBoxLayout(self.verticalLayoutWidget)
        self.verticalLayout.setMargin(0)

        self.groupFileSource = QtGui.QGroupBox(self.verticalLayoutWidget)

        self.horizontalLayoutWidget = QtGui.QWidget(self.groupFileSource)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(0, 20, 431, 51))
        self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setMargin(0)

        self.buttonFindFile = QtGui.QPushButton(self.horizontalLayoutWidget)
        self.horizontalLayout.addWidget(self.buttonFindFile)

        self.filePath = QtGui.QLineEdit(self.horizontalLayoutWidget)
        self.horizontalLayout.addWidget(self.filePath)

        self.verticalLayout.addWidget(self.groupFileSource)

        self.groupFadeIn = QtGui.QGroupBox(self.verticalLayoutWidget)

        self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupFadeIn)
        self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(0, 18, 431, 51))
        self.horizontalLayout_2 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_2)
        self.horizontalLayout_2.setMargin(0)

        self.fadeInSpin = QtGui.QSpinBox(self.horizontalLayoutWidget_2)
        self.fadeInSpin.setMaximum(36000)
        self.horizontalLayout_2.addWidget(self.fadeInSpin)

        self.fadeInLabel = QtGui.QLabel(self.horizontalLayoutWidget_2)
        self.fadeInLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.horizontalLayout_2.addWidget(self.fadeInLabel)

        self.fadeInExpSpin = QtGui.QDoubleSpinBox(self.horizontalLayoutWidget_2)
        self.fadeInExpSpin.setMinimum(0.1)
        self.fadeInExpSpin.setMaximum(10)
        self.fadeInExpSpin.setValue(3)
        self.horizontalLayout_2.addWidget(self.fadeInExpSpin)

        self.verticalLayout.addWidget(self.groupFadeIn)

        self.groupFadeOut = QtGui.QGroupBox(self.verticalLayoutWidget)

        self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupFadeOut)
        self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(0, 19, 431, 51))

        self.horizontalLayout_3 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_3)
        self.horizontalLayout_3.setMargin(0)

        self.fadeOutSpin = QtGui.QSpinBox(self.horizontalLayoutWidget_3)
        self.fadeOutSpin.setMaximum(36000)
        self.horizontalLayout_3.addWidget(self.fadeOutSpin)

        self.fadeOutLabel = QtGui.QLabel(self.horizontalLayoutWidget_3)
        self.fadeOutLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.horizontalLayout_3.addWidget(self.fadeOutLabel)

        self.fadeOutExpSpin = QtGui.QDoubleSpinBox(self.horizontalLayoutWidget_3)
        self.fadeOutExpSpin.setMinimum(0.1)
        self.fadeOutExpSpin.setMaximum(10)
        self.fadeOutExpSpin.setValue(1.5)
        self.horizontalLayout_3.addWidget(self.fadeOutExpSpin)

        self.verticalLayout.addWidget(self.groupFadeOut)

        self.groupWait = QtGui.QGroupBox(self.verticalLayoutWidget)

        self.horizontalLayoutWidget_1 = QtGui.QWidget(self.groupWait)
        self.horizontalLayoutWidget_1.setGeometry(QtCore.QRect(0, 25, 431, 51))
        self.horizontalLayout_1 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_1)
        self.horizontalLayout_1.setMargin(0)

        self.waitSpin = QtGui.QDoubleSpinBox(self.horizontalLayoutWidget_1)
        self.waitSpin.setMaximum(2000000)

        self.verticalLayout.addWidget(self.groupWait)

        self.groupGroups = QtGui.QGroupBox(self.verticalLayoutWidget)

        self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupGroups)
        self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(0, 20, 431, 51))

        self.horizontalLayout_4 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_4)
        self.horizontalLayout_4.setMargin(0)

        self.editGroups = QtGui.QLineEdit(self.horizontalLayoutWidget_4)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
        self.editGroups.setSizePolicy(sizePolicy)
        self.horizontalLayout_4.addWidget(self.editGroups)

        self.groupsEditLabel = QtGui.QLabel(self.horizontalLayoutWidget_4)
        self.groupsEditLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.horizontalLayout_4.addWidget(self.groupsEditLabel)

        self.verticalLayout.addWidget(self.groupGroups)

        self.checkEndFadeOut = QtGui.QCheckBox(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.checkEndFadeOut)

        self.checkPause = QtGui.QCheckBox(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.checkPause)

        self.checkLoop = QtGui.QCheckBox(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.checkLoop)

        self.checkStopAll = QtGui.QCheckBox(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.checkStopAll)

        self.pipelineEdit = QtGui.QPushButton(self.verticalLayoutWidget)
        self.verticalLayout.addWidget(self.pipelineEdit)

        self.editGroups.textEdited.connect(self.groupsValidation)
        self.pipelineEdit.clicked.connect(self.editPipeline)
        self.buttonFindFile.clicked.connect(self.selectFile)

        self.retranslateUi()

    def retranslateUi(self):
        self.groupFileSource.setTitle("File Source")
        self.buttonFindFile.setText("Find")
        self.groupFadeIn.setTitle("Fade In (sec/10)")
        self.fadeInLabel.setText("exponent:")
        self.groupFadeOut.setTitle("Fade Out (sec/10)")
        self.fadeOutLabel.setText("exponent:")
        self.groupWait.setTitle("Wait (sec)")
        self.groupGroups.setTitle("Edit Groups")
        self.groupsEditLabel.setText("Modify Groups [0,1,2,...,n]")
        self.checkEndFadeOut.setText("Enable end Fade Out")
        self.checkPause.setText("Enable Pause")
        self.checkLoop.setText("Enable Loop")
        self.checkStopAll.setText("Enable Stop All")
        self.pipelineEdit.setText("Pipeline Edit - Only for Advanced Users")

    def getConfiguration(self):
        conf = {}

        checkable = self.groupFileSource.isCheckable()

        if(not (checkable and not self.groupFileSource.isChecked())):
            conf['location'] = self.filePath.text()
        if(not (checkable and not self.groupFadeIn.isChecked())):
            conf['fadeIn'] = {'time': self.fadeInSpin.value(), 'exp': self.fadeInExpSpin.value()}
        if(not (checkable and not self.groupFadeOut.isChecked())):
            conf['fadeOut'] = {'time': self.fadeOutSpin.value(), 'exp': self.fadeOutExpSpin.value()}
        if(not (checkable and not self.groupGroups.isChecked())):
            if(self.groupsValidation(self.editGroups.text())):
                conf['groups'] = self.editGroups.text().split(',')
            else:
                conf['groups'] = []
        if(not (checkable and not self.groupGroups.isChecked())):
            conf['wait'] = self.waitSpin.value()
        if(self.checkEndFadeOut.checkState() != QtCore.Qt.PartiallyChecked):
            conf['endFadeOut'] = self.checkEndFadeOut.isChecked()
        if(self.checkPause.checkState() != QtCore.Qt.PartiallyChecked):
            conf['pause'] = self.checkPause.isChecked()
        if(self.checkLoop.checkState() != QtCore.Qt.PartiallyChecked):
            conf['loop'] = self.checkLoop.isChecked()
        if(self.checkStopAll.checkState() != QtCore.Qt.PartiallyChecked):
            conf['stopAll'] = self.checkStopAll.isChecked()
        if(self.oldPipeline != self.pipeline):
            if(self.pipeline.strip() != ''):
                conf['pipeline'] = self.pipeline
            elif(self.oldPipeline != ''):
                conf['pipeline'] = self.oldPipeline

        return conf

    def enableCheck(self, enable):
        self.groupFileSource.setCheckable(enable)
        self.groupFileSource.setChecked(False)

        self.groupFadeIn.setCheckable(enable)
        self.groupFadeIn.setChecked(False)

        self.groupFadeOut.setCheckable(enable)
        self.groupFadeOut.setChecked(False)

        self.groupWait.setCheckable(enable)
        self.groupWait.setChecked(False)

        self.groupGroups.setCheckable(enable)
        self.groupGroups.setChecked(False)

        self.checkEndFadeOut.setTristate(enable)
        if(enable):
            self.checkEndFadeOut.setCheckState(QtCore.Qt.PartiallyChecked)

        self.checkPause.setTristate(enable)
        if(enable):
            self.checkPause.setCheckState(QtCore.Qt.PartiallyChecked)

        self.checkLoop.setTristate(enable)
        if(enable):
            self.checkLoop.setCheckState(QtCore.Qt.PartiallyChecked)

        self.checkStopAll.setTristate(enable)
        if(enable):
            self.checkStopAll.setCheckState(QtCore.Qt.PartiallyChecked)

    def setConfiguration(self, conf):
        if(conf is None):
            self.pipeline = ''
            self.oldPipeline = ''
            return

        if('location' in conf):
            self.filePath.setText(conf['location'])
        else:
            self.filePath.setEnabled(False)
        if('fadeIn' in conf):
            if('time' in conf['fadeIn']):
                self.fadeInSpin.setValue(conf['fadeIn']['time'])
            else:
                self.fadeInSpin.setEnabled(False)
            if('exp' in conf['fadeIn']):
                self.fadeInExpSpin.setValue(conf['fadeIn']['exp'])
            else:
                self.fadeOutExpSpin.setEnabled(False)
        if('fadeOut' in conf):
            if('time' in conf['fadeOut']):
                self.fadeOutSpin.setValue(conf['fadeOut']['time'])
            else:
                self.fadeOutSpin.setEnabled(False)
            if('exp' in conf['fadeOut']):
                self.fadeOutExpSpin.setValue(conf['fadeOut']['exp'])
            else:
                self.fadeOutExpSpin.setEnabled(False)
        if('wait' in conf):
            self.waitSpin.setValue(conf['wait'])
        else:
            self.waitSpin.setEnabled(False)
        if('endFadeOut' in conf):
            self.checkEndFadeOut.setChecked(conf['endFadeOut'])
        else:
            self.checkEndFadeOut.setEnabled(False)
        if('pause' in conf):
            self.checkPause.setChecked(conf['pause'])
        else:
            self.checkPause.setEnabled(False)
        if('loop' in conf):
            self.checkLoop.setChecked(conf['loop'])
        else:
            self.checkLoop.setEnabled(False)
        if('stopAll' in conf):
            self.checkStopAll.setChecked(conf['stopAll'])
        else:
            self.checkStopAll.setEnabled(False)
        if('pipeline' in conf):
            self.pipeline = conf['pipeline']
            self.oldPipeline = self.pipeline
        else:
            self.pipelineEdit.setEnabled(False)
        if('groups' in conf):
            self.editGroups.setText(str(conf['groups']).strip('[]').replace('\'', ""))
        else:
            self.editGroups.setEnabled(False)

    def groupsValidation(self, groups):
        try:
            if(groups != ''):
                for g in groups.split(','):
                    int(g)
                self.editGroups.setStyleSheet('background-color: rgba(255, 255, 255, 255)')
                return True
            return False
        except ValueError:
            self.editGroups.setStyleSheet('background-color: rgba(255, 38, 0, 255)')
            return False

    def editPipeline(self):
        editUi = QTextInputDialog(initial=self.pipeline, parent=self)
        editUi.exec_()

        if(editUi.result() == QtGui.QDialog.Accepted):
            self.pipeline = editUi.plainTextEdit.toPlainText()

    def selectFile(self):
        file = QtGui.QFileDialog.getOpenFileName(self, "Choose file", QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MusicLocation), "Audio files (*.wav *.flac *.mp3 *.ogg);;Any file (*)")
        if file != '':
            self.filePath.setText(file)
